<?php
namespace app\admin\controller;
use app\common\model;
use app\common\model\Goods as GoodsModel;
use app\common\model\GoodsSku;
use app\common\model\GoodsSkuValue;
use app\common\model\Grade;
use app\common\model\GoodsCard;
use app\service\GoodsService;

class Goods extends Base
{   
    public $goodsModel;
    public $goodsTypeModel;
    public function __construct () {
        parent::__construct();
        $this->goodsModel = new model\Goods;
        $this->goodsTypeModel = new model\GoodsType;
    }

    /* 
     列表
     */
    public function list()
    {
        $where = [
            'mall_id' => $this->manager['mall_id']
        ];
        $input = input();
        $page = max(input('page'),1);
        $size = 20;
        if($input['shop_type']) {
            $where['shop_type'] = $input['shop_type'];
        }
        if($input['type_id']) {
            $where['type_id'] = $input['type_id'];
        }
        if($input['id']) {
            $where['id'] = $input['id'];
        }
        if ($input['keywords']) {
            $where['name'] = array('like', '%' . $input['keywords'] . '%');
        }
        $goodsList = $this->goodsModel->getPage($where,$page,$size,'ord desc,id desc');
        $total = $this->goodsModel->getCount($where);
        if(!$goodsList) {
            return returnJson(1,'');
        }
        foreach($goodsList as $k=>$v) {
            if($v['picture_list']) {
                $pics = json_decode($v['picture_list'],true);
                foreach($pics as $kk=>$vv) {
                    $pics[$kk]['url'] = tomedia($vv['path']);
                }
                $goodsList[$k]['picture_list'] = $pics;
            }
            $goodsList[$k]['picture'] = tomedia($v['picture']);
            $goodsList[$k]['content'] = !empty($v['content'])?$v['content']:'';
            if($v['shop_type']==4) {
                $goodsList[$k]['shop_type_text'] = Grade::id2name($v['grade']);
            }
        }
        return returnJson(0,'',[
            'list' => $goodsList,
            'size' => $size,
            'total' => $total
        ]);
    }

    
    /* 新增商品/修改商品 */
    public function edit () {
        if(request()->isPost()) {
            if($this->manager['mall_id']!=0) {
                //return returnJson(1,'您无权修改');
            }
            $input = input();
            if(!isset($input['name']) || !isset($input['price']) || !isset($input['picture_list'])) {
                return returnJson(1,'请填写完整');
            }
            if(!$input['tagList']) {
                $input['tagList'] = [];
            }
            $pics = json_decode($input['picture_list'],true);
            $data = array(
                'mall_id' => $this->manager['mall_id'],
                'name' => $input['name'],
                'price' => $input['price'],
                'shop_price' => $input['shop_price'],
                'picture_list' => $input['picture_list'],
                'picture' => $pics[0]['path'],
                'ord' => $input['ord'],
                'desc' => $input['desc'],
                'content' => $input['content'],
                'onsale' => $input['onsale'],
                'sale_val' => $input['sale_val'],
                'stock' => $input['stock'],
                'shop_type' => $input['shop_type'],
                'type_id' => $input['type_id'],
                'is_tejia' => in_array('is_tejia',$input['tagList'])?1:0,
                'is_tuijian' => in_array('is_tuijian',$input['tagList'])?1:0,
                'is_hot' => in_array('is_hot',$input['tagList'])?1:0,
                'is_new' => in_array('is_new',$input['tagList'])?1:0,
                'tag' => $input['tag'],
                'buy_min' => $input['buy_min'],
                'buy_max' => $input['buy_max'],
                'buy_step' => $input['buy_step'],
                'weight' => $input['weight'],
                'guige' => $input['guige'],
                'score_bili' => $input['score_bili']>1?1:$input['score_bili'],
                'money_dikou'=>$input['money_dikou']
            );
            if($this->manager['mall_id']==0 && ($input['shop_type']==1||$input['shop_type']==4)) {
                $data['is_pin']=1;
            }else{
                $data['is_pin']=0;
            }
            if(input('id')) {
                $data['id'] = input('id');
                $goods = $this->goodsModel->getOne(['id'=>$input['id']]);
                if($goods['mall_id']!=$this->manager['mall_id']) {
                    return returnJson(0,'无权修改');
                }
            }
            foreach($data as $k=>$v) {
                if(!isset($v)) {
                    unset($data[$k]);
                }
            }
            if($data['id']) {
                $res = $this->goodsModel->isUpdate(true)->save($data);
            }else{
                $res = $this->goodsModel->isUpdate(false)->save($data);
            }
            if($res) {
                return returnJson(0,'操作成功');
            }
            return returnJson(1,'网络异常，请重试');
        }
    }

    /* 删除商品 */
    public function delete () {
        if($this->manager['mall_id']!=0) {
            //return returnJson(1,'您无权修改');
        }
        $input = input();
        if(!$input['id']) {
            return returnJson(1,'error');
        }
        $goods = $this->goodsModel->getOne(['id'=>$input['id']]);
        if(!$goods) {
            return returnJson(1,'商品不存在');
        }
        if($goods['mall_id']!=$this->manager['mall_id']) {
            return returnJson(0,'无权修改');
        }
        $res = $this->goodsModel->where(['id'=>$input['id']])->delete();
        if($res) {
            $pics = json_decode($goods['picture_list'],true);
            foreach($pics as $v) {
                //model('qiniu')->remove($v['path']); 商品图片不能删除
            }
            return returnJson(0,'已删除');
        }else{
            return returnJson(1,'删除失败，请重试');
        }
    }

    /* 分类列表 */
    public function typeList () {
        $input = input();
        $where = [
            'mall_id' => $this->manager['mall_id'],
            'shop_type' => $input['shop_type']?$input['shop_type']:1
        ];
        $list = $this->goodsTypeModel->getAll($where);
        if(!$list) {
            return returnJson(0,'',[]);
        }
        return returnJson(0,'',$list);
    }

    /* 分类编辑 */
    public function typeEdit () {
        if($this->manager['mall_id']!=0) {
            //return returnJson(1,'您无权修改');
        }
        $input = input();
        if($input['name']){
            $data = array(
                'mall_id' => $this->manager['mall_id'],
                'name' => $input['name'],
//                'ord' => $input['ord'],
                'shop_type' => $input['shop_type']?$input['shop_type']:1
            );
            $res_data = model\GoodsType::getOne($data);
            if($res_data){
                return returnJson(1,'该分类已存在');
            }
        }else{
            return returnJson(1,'请输入分类名称');
        }
        $data['ord'] = $input['ord'];
        if($input['id']) {
            $data['id'] = $input['id'];
            $typeInfo = $this->goodsTypeModel->getOneById($input['id']);
            if($typeInfo['mall_id']!=$this->manager['mall_id']) {
                return returnJson(1,'无权修改');
            }
        }
        if($data['id']) {
            $res = $this->goodsTypeModel->isUpdate(true)->save($data);
        }else{
            $res = $this->goodsTypeModel->isUpdate(false)->save($data);
        }
        if($res) {
            return returnJson(0,'操作成功');
        }
        return returnJson(1,'网络异常，请重试');
    }

    /* 删除分类 */
    public function typeDelete () {
        if($this->manager['mall_id']!=0) {
            //return returnJson(1,'您无权修改');
        }
        $input = input();
        if(!$input['id']) {
            return returnJson(1,'error');
        }
        $goodsType = $this->goodsTypeModel->getOne(['id'=>$input['id']]);
        if(!$goodsType) {
            return returnJson(1,'商品分类不存在');
        }
        if($goodsType['mall_id']!=$this->manager['mall_id']) {
            return returnJson(1,'无权修改');
        }
        $res = $this->goodsTypeModel->where(['id'=>$input['id']])->delete();
        if($res) {
            return returnJson(0,'已删除');
        }else{
            return returnJson(1,'删除失败，请重试');
        }
    }

    /* sku详情 */
    public function skuDetail () {
        if($this->manager['mall_id']!=0) {
            //return returnJson(1,'您无权修改');
        }
        $input = input();
        $res = GoodsService::S()->skuDetail($input['goods_id']);
        $res['detail'] = GoodsModel::getOneById($input['goods_id']);
        return returnJson(0,'',$res);
    }

    /* 创建规格信息 */
    public function createSku () {
        if(!request()->isPost()) {
            exit(1);
        }
        if($this->manager['mall_id']!=0) {
            //return returnJson(1,'您无权修改');
        }
        $input = input();
        $goodsInfo = GoodsModel::getOneById($input['goods_id']);
        if($goodsInfo['mall_id']!=$this->manager['mall_id']) {
            return returnJson(1,'无权修改');
        }
        GoodsModel::where('id',$input['goods_id'])->update([
            's1' => $input['sku'][0]?$input['sku'][0]['name']: '',
            's2' => $input['sku'][1]?$input['sku'][1]['name']: ''
        ]);
        $sku = $input['sku'];
        GoodsSkuValue::where('goods_id',$goodsInfo['id'])->update([
            'status' => 0
        ]);
        //重置规格参数
        foreach($sku as $k=>$v) {
            $list = $v['list'];
            if($k!=0 && $k!=1) {
                continue;
            }
            if($k==0) {
                $skey = 's1';
            }else{
                $skey = 's2';
            }
            foreach($list as $kk=>$vv) {
                $item = [
                    'goods_id' => $goodsInfo['id'],
                    'type' => $skey,
                    'name' => $vv['name'],
                    'sn' => $vv['sn']
                ];
                $old = GoodsSkuValue::getOne($item);
                if($old) {
                    GoodsSkuValue::where($item)->update([
                        'status' => 1
                    ]);
                }else{
                    GoodsSkuValue::create($item);
                }
            }
        }
        //组装sku信息
        GoodsSku::where('goods_id',$goodsInfo['id'])->update([
            'status' => 0
        ]);
        $skuList = $input['skuList'];
        foreach($skuList as $k=>$v) {
            $nameArr = [];
            $snArr = explode('-',$v['sn']);
            if($v['s1']) {
                $s1 = GoodsSkuValue::getOne([
                    'type' => 's1',
                    //'name' => $v['s1'],
                    'sn' => $snArr[0],
                    'goods_id' => $goodsInfo['id']
                ]);
                $nameArr[] = $s1['name'];
            }
            if($v['s2']) {
                $s2 = GoodsSkuValue::getOne([
                    'type' => 's2',
                    //'name' => $v['s2'],
                    'sn' => $snArr[1],
                    'goods_id' => $goodsInfo['id']
                ]);
                $nameArr[] = $s2['name'];
            }
            $item = [
                'goods_id' => $goodsInfo['id'],
                's1' => $s1?$s1['id']:0,
                's2' => $s2?$s2['id']:0
            ];
            $old = GoodsSku::getOne($item);
            if($old) {
                GoodsSku::where($item)->update([
                    'status' => 1,
                    'price' => $v['price'],
                    'stock' => $v['stock'],
                    'name' => implode('-',$nameArr),
                    'sn' => implode('-',$snArr),
                ]);
            }else{
                $item['price'] = $v['price'];
                $item['stock'] = $v['stock'];
                $item['name'] = implode('-',$nameArr);
                $item['sn'] = implode('-',$snArr);
                GoodsSku::create($item);
            }
        }
        return returnJson(0,'操作成功');
    }

    //查询商品库存数量提示
    public function remindStock(){
        $where['mall_id']=$this->mall_id;
        if($this->mall_id==0){
            $this->ajax(200,'success');
        }
        //$where['onsale']=1;//上级商品
        $remindStock=2000;//商品到一定数量进行提示

        $backData['code']=200;
        $backData['message']='success';
        if($this->mall_id!=0){//积分商品金额小于50
            if($this->mall['jifen_money']<=$remindStock){
                $backData['info']="商户积分商城余额不足:{$this->mall['jifen_money']} 元请充值";
            }else{
                $backData['info']="商城积分余额:{$this->mall_id['jifen_money']}";
            }
            $backData['jifen_money']=$this->mall_id['jifen_money'];
        }
        echo json_encode($backData);die;/*
        $this->ajax(200,'success',$needBuhuoGoods);*/
    }


    /* 提货券列表 */
    public function cardlist()
    {
        $where = [];
        $input = input();
        if(isset($input['status'])) {
            $where['status'] = $input['status'];
        }
        if($input['number']) {
            $where['number'] = $input['number'];
        }
        if($input['uid']) {
            $where['uid'] = $input['uid'];
        }
        $page = max(input('page'),1);
        $size = 20;
        $goodsList = GoodsCard::getPage($where,$page,$size,'id desc');
        $total = GoodsCard::getCount($where);
        if(!$goodsList) {
            return returnJson(1,'');
        }
        foreach($goodsList as $k=>$v) {
            $goodsList[$k]['status_text'] = GoodsCard::getStatusText($v['status']);
        }
        return returnJson(0,'',[
            'list' => $goodsList,
            'size' => $size,
            'total' => $total
        ]);
    }
}
